//
//  ZFProfileViewController.swift
//  WeiBoAPP
//
//  Created by 张学飞 on 2018/12/28.
//  Copyright © 2018 zxf. All rights reserved.
//

import UIKit

class ZFProfileViewController: ZFBaseViewController {

    lazy var dataList = [String]()
    lazy var dataBaseList = [DBModel]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "测试数据库";
        // Do any additional setup after loading the view.
        setupData()
    
    }
    
    override func setupUI() {
        super.setupUI()
    }
    
    override func setupTableView() {
//        super.setupTableView()
        if tableView != nil {
            return
        }
        
        tableView = UITableView(frame: view.bounds, style: .grouped)
        
        view.addSubview(tableView!)
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        //设置数据源方法
        tableView?.dataSource = self
        tableView?.delegate = self
        tableView?.contentInset = UIEdgeInsets(top:navigationBar.bounds.height,
                                               left: 0,
                                               bottom:tabBarController?.tabBar.bounds.height ?? 49,
                                               right: 0)
        //修改指示器的缩进,强行解包为了拿到一个必有的 inset
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        //刷新控件
        refreshController = UIRefreshControl()
        tableView?.addSubview(refreshController!)
        refreshController?.addTarget(self, action:#selector(refreshData), for: .valueChanged)
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView?.register(UINib.init(nibName: "ZFProfileTableViewCell", bundle: nil), forCellReuseIdentifier: "ProfileCell")
    }
    
    // 打开数据库，创建表
    func setupData() {
        
        // 元素
        dataList.append(contentsOf: ["添加元素","清空表","刷新所有元素"])
        // 打开数据库
        DataBaseManager.shareManager().openDB()
        // 创建表
        DataBaseManager.shareManager().createTable()
        // 读取数据
        let arr:[DBModel]  = DataBaseManager.shareManager().readAllDataModel()
        dataBaseList.append(contentsOf: arr)
        
    }
    
    deinit {
    
        print("销毁控制器:ZFProfileViewController")
        
    }
    
}

extension ZFProfileViewController {
    
     func numberOfSections(in tableView: UITableView) -> Int {
        
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return dataList.count
        }
        return dataBaseList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        if indexPath.section == 0 {
            let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
            cell.textLabel?.text = dataList[indexPath.row]
            
            return cell
        }
        // 数据库cell
        let dbCell:ZFProfileTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell") as! ZFProfileTableViewCell
        let dbModel = dataBaseList[indexPath.row];
        dbCell.titleLabel?.text = dbModel.title ?? "" + "db_id:\(dbModel.db_Id)"
        dbCell.subTitleLabel?.text = dbModel.subTitle
        dbCell.dateLabel.text = String(describing: dbModel.date)
         
        // 弱引用  // 解决方式一: weak
//        weak var weakSelf = self 或  [weak self]
        dbCell.deleteButtonBlock = {[weak self]() in
            DataBaseManager.shareManager().deleteModel(model: dbModel)
            self?.loadDataRefresh()
        }
        
        return dbCell
    }
    
    
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 0 {
            
            if indexPath.row == 0 {
                
                // 插入
                let dbModel = DBModel()
                let today = Date()
                
                dbModel.title = "我是谁" + "\(arc4random() % 100)"
                dbModel.subTitle = "哈哈哈"
                dbModel.date = today
                
                print("today = \(today)")// 打印出的时间是GTM时间，比北京时间早了8个小时

                
                DataBaseManager.shareManager().insertModel(model: dbModel)
                loadDataRefresh()
            }else if (indexPath.row == 1){
                // 删除
                DataBaseManager.shareManager().deleteALLModel()
                loadDataRefresh()
            }else if (indexPath.row == 2){
                // 刷新
                loadDataRefresh()
            }else if (indexPath.row == 3){
                
                
            }else if (indexPath.row == 4){
                
                
            }
            
            
        }else{
            
            
            
            
        }
        
    }
    
    
    func loadDataRefresh() {
        let arr:[DBModel]  = DataBaseManager.shareManager().readAllDataModel()
        dataBaseList.removeAll()
        dataBaseList.append(contentsOf: arr)
        self.tableView?.reloadData()
    }
    

    
}
